package com.wss.lsl.test.driven.concurrent.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * 累计计算任务
 * 
 * @author weiss
 *
 */
public class CountTask extends RecursiveTask<Integer> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final int threshold = 2;
	private int start;
	private int end;

	public CountTask(int start, int end) {
		super();
		this.start = start;
		this.end = end;
	}

	@Override
	protected Integer compute() {

		boolean canCompute = (end - start) <= threshold;
		int sum = 0;
		if (canCompute) {
			for (int i = start; i <= end; i++) {
				sum += i;
			}
		} else {
			int middle = (end + start) / 2;
			CountTask leftTask = new CountTask(start, middle);
			CountTask rightTask = new CountTask(middle + 1, end);

			leftTask.fork();
			rightTask.fork();

			sum += leftTask.join();
			sum += rightTask.join();
		}

		return sum;
	}

}
